<?php


namespace app\api\controller;


use app\api\model\UserModel;
use app\api\validate\UserValidate;
use app\BaseController;
use think\facade\Db;

class User extends BaseController
{
    public function sendCode(){
        $mobile = input('mobile');
        //验证验证码
        $code = sendAliSms($mobile);
        if($code['code'] == 1){
            return success('发送成功');
        }else{
            return error($code['msg']);
        }
    }
    //注册
    public function register(){
        //接收数据
        $data = input('post.');
        //查重
        $mobile = UserModel::where('mobile',$data['mobile'])->find();
        if($mobile){
            return error('账号已存在');
        }
        //验证
        $validate = new UserValidate();
        $result = $validate->scene('register')->check($data);
        //判断
        if(!$result){
            return error($validate->getError());
        }
        //验证验证码是否存在
        // $code = Db::name('sms_code_log')->where('mobile',$data['mobile'])->find();
        $check = checkSmsCode($data['mobile'],$data['code']);
        if(!$check){
            return error('验证码错误');
        }
        //密码
        $randStr = createRandStr(8);
        $data['password'] = md5($data['password'].$randStr);
        $data['salt'] = $randStr;
        $user = UserModel::create($data);

        //入库
        if($user){
            return success('注册成功');
        }else{
            return error('注册失败');
        }
    }
    //登录
    public function login(){
        //接收
        $data = input('post.');
        //验证
        $validate = new UserValidate();
        $result = $validate->scene('login')->check($data);
        //判断
        if(!$result){
            return error($validate->getError());
        }
        //查询账号
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if(!$user){
            return error('该账号不存在');
        }
        if(md5($data['password'].$user['salt']) != $user['password']){
            return error('密码错误');
        }
        return success('登录成功');
    }
}